package com.example.looktv

import android.content.Context
import android.preference.PreferenceManager
import android.util.Log
import com.google.gson.Gson
import com.google.gson.JsonArray
import org.jsoup.Jsoup
import org.jsoup.select.Elements
import kotlin.concurrent.thread

class TvLoader {
    companion object {
        val TAG = "TVLoader"
        val host = "http://m1.91kds.cn/"
        val cctv = host +"index1_ys.html"
        val ws = host + "index2_ws.html"
        fun load(context: Context):List<TvSite>{

            log("start load")
            var uris = loadCache(context)
            if (uris.size>0){
                thread(start = true){
                    updateCache(context)
                }
                return uris
            }
            uris = updateCache(context)
            return uris
        }

        private fun updateCache(context: Context):List<TvSite>{
            var uris = ArrayList<TvSite>()
            var elements = loadChannel(cctv)
            elements?.forEach {
                uris.add(TvSite(name = it.text(),uris = loadUriOf(it.attr("href"))))
            }
            elements = loadChannel(ws)
            elements?.forEach {
                uris.add(TvSite(name = it.text(),uris = loadUriOf(it.attr("href"))))
            }
            val defaultSharedPreferences =
                PreferenceManager.getDefaultSharedPreferences(context)
            defaultSharedPreferences.edit().putString("tvs", Gson().toJson(uris)).commit()
            return uris
        }

        private fun loadChannel(channel: String): Elements? {
            val doc = Jsoup.connect(channel).get()
            val elements = doc.select("ul>li>a")
            return elements
        }

        private fun loadCache(context: Context): List<TvSite> {
            var uris = ArrayList<TvSite>()
            val defaultSharedPreferences =
                PreferenceManager.getDefaultSharedPreferences(context)
            val tvs = defaultSharedPreferences.getString("tvs", null)
            if (tvs == null) {
                return uris
            }
            var gson = Gson()
            val root = gson.fromJson(tvs, JsonArray::class.java)
            root.forEach {
                uris.add(gson.fromJson(it,TvSite::class.java))
            }
            return uris
        }

        private fun loadUriOf(href: String?):List<String> {
            val doc = Jsoup.connect(host + href).get()
            val urls = doc.select("#plauURL>option")
            return urls.map { it.`val`() }.filter { it.startsWith("http") }

        }

        fun log(msg:String){
            Log.d(TAG,msg)
        }
    }


}
